﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Universum.Infrastructure.Persistence;
using Universum.Model.Domain;
using System.Security.Principal;
using Universum.Infrastructure.Persistence.Queries.User;
using System.Text.RegularExpressions;
using FlimFlan.ReadableRex;
using Universum.Infrastructure.Configuration;
namespace Universum.Infrastructure.Security
{
	public class RoleServiceImpl : IRoleService
	{
		IRepository _Repository;
		IPrincipal _Principal;
		public RoleServiceImpl(IRepository repository,
			IPrincipal principal)
		{
			_Repository = repository;
			_Principal = principal;
			string pattern = Pattern.With.AtBeginning.NonDigit.Repeat.Exactly(4)
				.Digit.Repeat.Exactly(4).ToString();

			studentRegistrationRegex =
				new Regex(
					pattern
				,
				 RegexOptions.Compiled);
			
		
		}
		public Regex studentRegistrationRegex;
		public Regex teacherRegistrationRegex;
		#region IRoleService Members

		public bool IsInRole(string roleName)
		{
			if (_Principal == null || _Principal.Identity.Name == "anonymous") return false;

			var result =  Enum.Parse(typeof(RoleType), roleName, true);
			if (result.IsNotNull() && result.Cast<RoleType>().IsNotNull())
			{
				switch (result.Cast<RoleType>())
				{
					case RoleType.Student:
						bool resultValue = studentRegistrationRegex.Match(_Principal.Identity.Name).Success;
						return resultValue;
						
					case RoleType.Teacher:
						bool returnValue = 
							studentRegistrationRegex
							.Match(_Principal.Identity.Name).Success
							.IsFalse() 
							&& _Principal.Identity.Name.ToLower().Equals("secretary")
							.IsFalse();
						return returnValue;
					case RoleType.Secretary:
						return
							_Principal.Identity.Name.ToLower()
							.Equals("secretary");
						
					
						
				}
				
			}
			return false;
			//return _Repository.Query(
			//	new RoleByNameAndUsername(roleName,
			//	_Principal.Identity.Name)).SingleOrDefault() != null;
		}
		public enum RoleType
		{
			Student,
			Teacher,
			Secretary
		}
		

		#endregion
	}
}
